<template>
  <div class="login-container">

    <div class="login-form">
      <div class="qrcode_login" @click="loginPage(3)" v-if="loginForm.loginType<3">
        <span class="wechat_notice">微信登录</span>
        <svg-icon icon-class="qrcode"></svg-icon>
      </div>
      <div class="qrcode_login" @click="loginPage(2)" v-if="loginForm.loginType==3">
        <span class="wechat_notice">手机登录</span>
        <svg-icon icon-class="mobile"></svg-icon>
      </div>
      <div v-if="loginForm.loginType==3">
        <div class="title-container">
          <h3 class="title">群众呼声麻辣问政 - 机构管理后台</h3>
        </div>
        <div class="wechat-qrcode">
          <vue-qr
            v-if="wechatData.qrcodeText"
            :size="250"
            :margin="0"
            :auto-color="true"
            :dot-scale="1"
            :text="wechatData.qrcodeText"
          />
          <div class="mask" v-if="wechatData.error">二维码失效，<span @click="refqrcode">刷新</span></div>
          <div v-else class="default_qrcode" v-loading="wechatData.qrcode"></div>

          <p>微信扫一扫</p>
        </div>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" auto-complete="on" v-show="loginForm.loginType<3"
               label-position="left">

        <div class="title-container">
          <h3 class="title">群众呼声麻辣问政 - 机构管理后台</h3>
        </div>
        <div class="loginTypebtn">
          <div :class="[loginForm.loginType==1?'cur':'']" @click="loginForm.loginType=1">麻辣社区</div>
          <div :class="[loginForm.loginType==2?'cur':'']" @click="loginForm.loginType=2">手机短信</div>
        </div>

        <div v-if="loginForm.loginType==1">
          <el-form-item>
            <el-input
              prefix-icon="el-icon-user"
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入麻辣社区账号"
              name="phone"
              type="text"
              tabindex="1"
              size="medium"
              auto-complete="on"
            />
          </el-form-item>

          <el-form-item>
            <div style="display: flex">
              <el-input
                prefix-icon="el-icon-c-scale-to-original"
                v-model="loginForm.password"
                placeholder="请输入密码"
                name="code"
                tabindex="2"
                type="password"
                auto-complete="on"
              />
            </div>
          </el-form-item>
        </div>
        <div v-else-if="loginForm.loginType==2">
          <el-form-item prop="phone">
            <el-input
              prefix-icon="el-icon-mobile"
              ref="username"
              v-model="loginForm.phone"
              placeholder="请输入手机号码"
              name="phone"
              type="text"
              tabindex="1"
              size="medium"
              auto-complete="on"
            />
          </el-form-item>

          <el-form-item prop="code">
            <div style="display: flex">
              <el-input
                style="width:240px;"
                prefix-icon="el-icon-c-scale-to-original"
                v-model="loginForm.code"
                placeholder="请输入6位短信验证码"
                name="code"
                tabindex="2"
                maxlength="6"
                auto-complete="on"
              />
              <el-button style="margin-left:15px;width:calc(100% - 260px)" :type="codeBtnType" plain @click="sendSms"
                         :disabled="countdown>0?true:false" :loading="codeLoading">
                {{ countdown > 0 ? countdown + '秒可重发' : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </div>
        <el-button :loading="loading" type="primary" style="width:100%;height:60px;font-size:20px;"
                   @click.native.prevent="handleLogin">登录后台
        </el-button>


      </el-form>
    </div>
    <div class="tips" style="margin-top:40px;">
      <div style="color:#20a0ff;text-align: center;cursor: pointer" @click="goReg"><i class="el-icon-s-check"/>
        机构入驻，点击这里
      </div>
      <div style="color:#999;text-align: center;margin-top:10px;">Powered by Mala' developer Xu Xiaolong</div>
      <div style="color:#999;margin-top:10px;text-align: center">Copyright@2003-2023 mala.cn all rights reserved</div>
    </div>
  </div>
</template>

<script>
import {getQrcodeRandid, getWechatTicket, loginSendCode} from '@/api/user'
import VueQr from 'vue-qr';

export default {
  components: {
    VueQr,
  },
  name: 'Login',
  data() {

    const validatePhone = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9]|16[0-9]|19[0-9])[0-9]{8}$/;
      if (regMobile.test(value)) {
        callback()
      } else {
        callback(new Error('手机号码格式不正确'))
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('验证码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      wechatData: {
        qrcode: true,
        qrcodeText: '',
        error: false,
      },
      wechatUser: {
        openid: ''
      },
      loginForm: {
        password:'',
        username:'',
        phone: '',
        code: '',
        loginType:1,
      },
      countdown: 0,
      codeBtnType: 'primary',
      codeLoading: false,
      loginRules: {
        phone: [{required: true, trigger: 'blur', validator: validatePhone}],
        code: [{required: true, trigger: 'blur', validator: validateCode}]
      },
      loading: false,
      redirect: undefined,
      timer: '',
      qrcodetimer: '',
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    'wechatUser.uid': function (newval, b) {
      if (newval > 0) {
        clearInterval(this.qrcodetimer)
      }
      //使用$once(eventName, eventHandler)一次性监听事件
      this.$once('hook:boforeDestory', () => {
        clearInterval(this.qrcodetimer)
      })
    }
  },
  mounted() {
    window.addEventListener('keydown', this.handleKeyDown);
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    handleKeyDown(event){
      if (event.key === 'Enter') {
        this.handleLogin()
      }
    },
    goReg() {
      this.$router.push({path: '/reg'})
    },
    refqrcode() {
      clearInterval(this.qrcodetimer)
      this.qrcodetimer = '';
      this.wechatData.qrcode = true
      this.wechatData.error = false
      getWechatTicket().then(r => {
        this.wechatData.qrcode = false
        this.wechatData.qrcodeText = r.data.qrcodeText
        this.starQueryRandid(r.data.randid);
      })
    },
    loginPage(t) {
      this.loginForm.loginType = t
      if (t == 2) {
        this.wechatData.qrcodeText = ''
        this.wechatData.qrcode = true
        getWechatTicket().then(r => {
          this.wechatData.qrcode = false
          this.wechatData.qrcodeText = r.data.qrcodeText
          this.starQueryRandid(r.data.randid);
        })
      } else {
        clearInterval(this.qrcodetimer)
      }
    },
    starQueryRandid(randid) {
      this.qrcodetimer = setInterval(() => {
        getQrcodeRandid({randid: randid}).then(r => {
          this.wechatUser = r.data
          if (r.data.token) {
            this.$message.success('登录成功，请稍后....');
            this.$store.dispatch('user/tokenLogin', {token: r.data.token}).then(() => {
              this.$router.push({path: this.redirect || '/'})
            })
          }
        }, data => {
          this.wechatData.error = true
          1
          clearInterval(this.qrcodetimer)
        })
      }, 3000)
    },
    sendSms() {
      let mobile = this.loginForm.phone
      let regMobile = /^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9]|16[0-9]|19[0-9])[0-9]{8}$/;
      if (regMobile.test(mobile)) {
        this.codeLoading = true;
        loginSendCode({phone: this.loginForm.phone}).then(r => {
          this.codeLoading = false
        }, data => {
          this.countdown = 0
          this.codeLoading = false
          this.codeBtnType = 'primary'
          clearInterval(this.timer);
          this.timer = null;
        })
        this.codeBtn()
      } else {
        this.$message.error('手机号不正确');
      }
    },
    codeBtn(bool) {
      this.countdown = 120
      this.codeBtnType = 'info'
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          this.codeBtnType = 'primary'
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({path: this.redirect || '/'})
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('发生了一些错误')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less">

.login-container {
  .el-input__inner {
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    padding-left: 40px;
  }

  .el-input__prefix {
    left: 10px;
  }

  .el-input__icon {
    font-size: 18px;
    line-height: 50px;
    color: #666;
  }
}
</style>
<style lang="scss" scoped>
$bg: #ededed;
$dark_gray: #889aa4;
$light_gray: #000;
.qrcode_login {
  position: absolute;
  right: 5px;
  top: 5px;
  cursor: pointer;

  &:hover {
    .svg-icon {
      color: #07c160;
    }
  }

  .svg-icon {
    font-size: 40px;
    color: #666;
    border-bottom-left-radius: 80px;
  }

  .wechat_notice {
    width: 80px;
    background: #999;
    color: #fff;
    text-align: center;
    padding: 5px 5px;
    border-radius: 2px;
    position: absolute;
    right: 50px;
    top: 5px;
    font-size: 14px;;

    &:after {
      position: absolute;
      content: "";
      right: -15px;
      bottom: 6px;
      width: 0;
      height: 0;
      border-top: 6px solid transparent;
      border-right: 8px solid transparent;
      border-bottom: 6px solid transparent;
      border-left: 8px solid #999;
    }
  }
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    height: 420px;
    padding: 60px 35px;
    filter: drop-shadow(0 0 10px rgba(0, 0, 0, 0.3));
    background: #fff;
    margin: 0 auto;
    margin-top: 160px;
    overflow: hidden;

    .wechat-qrcode {
      height: 250px;
      width: 250px;
      margin: 0 auto;
      text-align: center;
      margin-top: -20px;
      position: relative;

      .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 250px;
        height: 250px;
        text-align: center;
        background: rgba(0, 0, 0, .8);
        font-size: 20px;
        color: #fff;
        line-height: 250px;

        span {
          color: #20a0ff;
          cursor: pointer;
        }
      }

      img, .default_qrcode {
        width: 250px;
        height: 250px
      }

      p {
        color: #7e8081;
        font-size: 16px;
        margin: 15px 0;
      }
    }
  }

  .tips {
    font-size: 14px;

    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #666;
    position: absolute;
    vertical-align: middle;
    width: 30px;

    i {
      font-size: 20px;
      color: #666;
    }
  }
  .loginTypebtn{
    display: flex;
    margin:5px 0 20px 0;
    >div{
      padding-bottom: 10px;
      margin-right:30px;
      font-size:16px;
      color:#888;
      cursor: pointer;
      &.cur{
        color:#20a0ff;
        border-bottom: 2px solid #20a0ff;
        font-weight: bold;
      }
    }
  }
  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
